package cn.com.yang.datastruct.link;

/**
 * 单项链表
 * @since 2023.07.30
 */
public class SingleLink {
    private int size;//节点数
    private Node head;//head就是头节点指针

    public SingleLink(){
        size=0;
        head=null;
    }
    private  class Node{
        private Object data;
        private Node next;//指针指向下个节点
        public Node(Object data){
            this.data = data;
        }

        @Override
        public String toString() {
            return "Node{" +
                    "data=" + data +
                    ", next=" + next +
                    '}';
        }
    }
    //添加节点,在链表头添加
    public Object addHead(Object data){
        Node newNode = new Node(data);
        if (size ==0){
            head = newNode;
        } else{
            newNode.next=head;
            newNode= head;
        }
        size++;
        return newNode;
    }
    //链表头部删除
    public  Object delHead(){
        Object obj = head.data;
        head=head.next;
        size --;
        return obj;
    }
    //查找节点
    public Node find(Object data){
        Node current = head;
        int tempSize = size;
        while (tempSize>0){
            if (current.data.equals(data)){
                return current;
            }else {
                current = current.next;
            }
            tempSize--;
        }
        return null;
    }
    //判断链表是不是空
    public boolean isEmpty(){
        return size==0;
    }
    //删除指定的节点
    public boolean delNode(Object val){
        if (isEmpty()){
            return false;
        }
         Node current = head;
         Node previous = head;
         while (!val.equals(current.data)){
             if (current.next==null){//扫描到尾部，没找到
                 return false;
             }else {            //扫描当前节点，移动到下一个节点
                 previous = current;
                 current = current.next;        
             }
         }
         //循环终止了，继续执行下面的语句
        //对找到的节点及时删除
        if (current==head){
            head = head.next;
            size--;
        }else {
            previous.next = current.next;
            size--;
        }
        return true;
    }
    //遍历所有节点信息
    public void dispaly(){
        if (isEmpty()){
            System.out.println("[]");
        }
        Node current = head;
        int tempSzie =size;
        if (tempSzie==1){
            System.out.println("["+head+"]");
            return;
        }
        while (tempSzie>0){
            if (current==head){
                System.out.println("["+current.data+"->");
            } else if (current.next==null) {
                System.out.println(current.data+"]");
            }else{
                System.out.println(current.data+"->");
            }
            tempSzie--;
            current=current.next;
        }
        System.out.println();
    }
}
